<html xmlns="http://www.w3.org/1999/xhtml" xmlns:c="http://java.sun.com/jstl/core"
      xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"
      xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:t="http://myfaces.apache.org/tomahawk"
      xmlns:v="http://corejsf.com/validator">

    <f:view>
        <f:loadBundle var="text" basename="#{paymentForm.bundleName}"/>
        <head>
            <title>#{text['paymentDetail.title']}</title>
            <meta name="heading" content="#{text['paymentDetail.heading']}"/>
            <meta name="menu" content="OperationMenu"/>
        </head>

        <div class="separator"></div>

        <h:form id="paymentForm">
            <h:inputHidden value="#{paymentForm.payment.id}" id="id"/>

            <h:panelGrid columns="3">

                <h:panelGroup styleClass="buttonBar right">
                    <h:commandButton value="#{text['button.save']}" action="#{paymentForm.save}" id="save" styleClass="button"/>
                    <c:if test="${not empty paymentForm.payment.id}">
                        <h:commandButton value="#{text['button.revoke']}" action="#{paymentForm.cancel}" immediate="true"
                                         id="revoke" styleClass="button"/>
                        <c:if test="#{paymentForm.payment.status != 'CANCELADO'}">
                            <h:commandButton id="print" value="#{text['button.print']}"
                                             onclick="return printReceipt(#{paymentForm.payment.id});"
                                             styleClass="button"/>
                        </c:if>
                    </c:if>
                    <h:commandButton value="#{text['button.close']}" action="cancel" immediate="true"
                                     id="close" styleClass="button"/>
                </h:panelGroup>
                <h:outputText/><h:outputText/>

                <h:panelGroup styleClass="info">
                    <c:choose>
                        <c:when test="${param.from == 'list' or empty paymentForm.payment.id}">
                            <h:outputText value="#{text['paymentDetail.admin.message']}"/>
                        </c:when>
                        <c:otherwise><h:outputText value="#{text['paymentDetail.message']}"/></c:otherwise>
                    </c:choose>
                </h:panelGroup>
                <h:outputText/><h:outputText/>

                <h:panelGroup>
                    <div>
                        <div class="left">
                            <h:outputLabel styleClass="desc" for="_id" value="#{text['payment.id']}"/>
                            <h:inputText styleClass="text medium" id="_id" value="#{paymentForm.payment.id}" readonly="true"/>
                            <t:message for="_id" styleClass="fieldError"/>
                        </div>
                        <div>
                            <h:outputLabel styleClass="desc" for="date" value="#{text['payment.date']}"/>
                            <h:inputText styleClass="text medium" id="date" value="#{paymentForm.payment.date}" readonly="true">
                                <f:convertDateTime pattern="dd/MM/yyyy"/>
                            </h:inputText>
                            <t:message for="date" styleClass="fieldError"/>
                        </div>
                    </div>
                </h:panelGroup>

                <h:outputText/><h:outputText/>

                <h:outputLabel for="description" styleClass="desc" value="#{text['payment.description']}"/>
                <t:message for="description" styleClass="fieldError"/>
                <h:inputText value="#{paymentForm.payment.description}" id="description" styleClass="text large" readonly="#{paymentForm.isView}">
                    <v:commonsValidator client="true" type="required" arg="#{text['payment.description']}"/>
                </h:inputText>

                <h:outputLabel for="receiptNumber" styleClass="desc" value="#{text['payment.receiptNumber']}"/>
                <t:message for="receiptNumber" styleClass="fieldError"/>
                <h:inputText value="#{paymentForm.payment.receiptNumber}" id="receiptNumber" styleClass="text large" readonly="#{paymentForm.isView}">
                    <v:commonsValidator client="true" type="required" arg="#{text['payment.receiptNumber']}"/>
                </h:inputText>

                <h:panelGroup>
                    <div>
                        <div class="left">
                            <h:outputLabel for="currency" styleClass="desc" value="#{text['payment.currency']}"/>
                            <h:selectOneMenu value="#{paymentForm.payment.currency}" id="currency" required="true" styleClass="select" disabled="#{paymentForm.isView}"
                                             valueChangeListener="#{paymentForm.processCurrencyChange}" onchange="this.form.submit();">
                                <t:selectItems value="#{paymentForm.currencies}" var="currency" itemLabel="#{currency.description}" itemValue="#{currency}"/>
                                <f:converter converterId="objconverter"/>
                                <v:commonsValidator client="true" type="required" arg="#{text['payment.currency']}"/>
                            </h:selectOneMenu>
                            <t:message for="currency" styleClass="fieldError"/>
                        </div>
                        <div>
                            <h:outputLabel for="paymentType" styleClass="desc" value="#{text['payment.paymentType']}"/>
                            <h:selectOneMenu value="#{paymentForm.payment.type}" id="paymentType" styleClass="select" disabled="#{paymentForm.isView}">
                                <t:selectItems value="#{paymentForm.paymentTypes}" var="paymentType" itemLabel="#{paymentType.description}" itemValue="#{paymentType}"/>
                                <f:converter converterId="objconverter"/>
                            </h:selectOneMenu>
                            <t:message for="paymentType" styleClass="fieldError"/>
                        </div>
                    </div>
                </h:panelGroup>
                <h:outputText/><h:outputText/>

                <h:outputLabel for="company" styleClass="desc" value="#{text['payment.company']}"/>
                <h:selectOneMenu value="#{paymentForm.company}" id="company" required="true" styleClass="select" disabled="#{paymentForm.isView}"
                                 valueChangeListener="#{paymentForm.processCompanyChange}" onchange="this.form.submit();">
                    <f:selectItem itemLabel="Todas"/>
                    <t:selectItems value="#{paymentForm.companies}" var="company" itemLabel="#{company.description}" itemValue="#{company}"/>
                    <f:converter converterId="objconverter"/>
                    <v:commonsValidator client="true" type="required" arg="#{text['payment.company']}"/>
                </h:selectOneMenu>
                <t:message for="company" styleClass="fieldError"/>
                <h:outputText/><h:outputText/>

                <h:outputLabel for="amount" styleClass="desc" value="#{text['payment.amount']}"/>
                <t:message for="amount" styleClass="fieldError"/>
                <h:inputText value="#{paymentForm.payment.amount}" id="amount" required="true" styleClass="text medium" disabled="#{paymentForm.isView}"
                             onchange="return distribute();">
                    <f:convertNumber type="number" pattern="#,##0.00;(#,##0.00)"/>
                    <v:commonsValidator client="true" type="required" arg="#{text['payment.amount']}"/>
                </h:inputText>                
                <h:outputText/><h:outputText/>

                <t:htmlTag value="div" id="viewTable" rendered="#{paymentForm.isView}">
                    <t:dataTable value="#{paymentForm.payment.paymentDetails}" var="detail" width="100%" id="paidInvoices"
                                 styleClass="scrollerTable table">
                        <t:column width="10%">
                            <f:facet name="header">
                                <t:outputText value="#{text['payment.invoice']}"/>
                            </f:facet>
                            <t:outputText value="#{detail.invoice.id}"/>
                        </t:column>
                        <t:column width="20%">
                            <f:facet name="header">
                                <t:outputText value="#{text['invoice.description']}"/>
                            </f:facet>
                            <t:outputText value="#{detail.invoice.description}"/>
                        </t:column>
                        <t:column width="20%">
                            <f:facet name="header">
                                <t:outputText value="#{text['invoice.payment']}"/>
                            </f:facet>
                            <t:outputText value="#{detail.amount}">
                                <f:convertNumber type="number" pattern="#,##0.00;(#,##0.00)"/>
                            </t:outputText>
                        </t:column>                        
                    </t:dataTable>
                </t:htmlTag>
                <t:htmlTag value="div" id="editTable" rendered="#{!paymentForm.isView}">
                    <t:dataTable value="#{paymentForm.invoices}" var="invoice" width="100%" id="invoices"
                                 styleClass="scrollerTable table" rowIndexVar="indx"
                                 preserveDataModel="true">
                        <t:column width="10%">
                            <f:facet name="header">
                                <t:outputText value="#{text['payment.invoice']}"/>
                            </f:facet>
                            <t:outputText value="#{invoice.id}"/>
                        </t:column>
                        <t:column width="20%">
                            <f:facet name="header">
                                <t:outputText value="#{text['invoice.description']}"/>
                            </f:facet>
                            <t:outputText value="#{invoice.description}"/>
                        </t:column>
                        <t:column width="10%">
                            <f:facet name="header">
                                <t:outputText value="#{text['invoice.total']}"/>
                            </f:facet>
                            <t:inputText id="totalLocal" style="text-align: right" value="#{invoice.localAmount - invoice.localAmountPaid}" disabled="true"
                                         rendered="#{paymentForm.payment.currency.symbol == 'C$'}">
                                <f:convertNumber type="number" pattern="#,##0.00;(#,##0.00)"/>
                            </t:inputText>
                            <t:inputText id="foreignLocal" style="text-align: right" value="#{invoice.foreignAmount - invoice.foreignAmountPaid}" disabled="true"
                                         rendered="#{paymentForm.payment.currency.symbol == '$'}">
                                <f:convertNumber type="number" pattern="#,##0.00;(#,##0.00)"/>
                            </t:inputText>
                            <f:facet name="footer">
                                <h:panelGrid>
                                    <t:inputText id="_plocaltotal" value="#{paymentForm.localPendingAmount}" style="text-align: right;" readonly="true"
                                                 rendered="#{paymentForm.payment.currency.symbol == 'C$'}">
                                        <f:convertNumber type="number" pattern="#,##0.00;(#,##0.00)"/>
                                    </t:inputText>
                                    <t:inputText id="_ptotal" value="#{paymentForm.pendingAmount}" style="text-align: right;" readonly="true"
                                                 rendered="#{paymentForm.payment.currency.symbol == '$'}">
                                        <f:convertNumber type="number" pattern="#,##0.00;(#,##0.00)"/>
                                    </t:inputText>
                                </h:panelGrid>
                            </f:facet>
                        </t:column>
                        <t:column width="10%">
                            <f:facet name="header">
                                <t:outputText value="#{text['invoice.currency']}"/>
                            </f:facet>
                            <t:outputText value="#{paymentForm.payment.currency}"/>
                        </t:column>
                        <t:column width="10%">
                            <f:facet name="header">
                                <t:outputText value="#{text['invoice.amountPaid']}"/>
                            </f:facet>
                            <t:inputText id="amountPaid" style="text-align: right" value="#{invoice.currentPayment}"
                                         onchange="return distribute();">
                                <f:convertNumber type="number" pattern="#,##0.00;(#,##0.00)"/>
                            </t:inputText>
                        </t:column>
                        <t:column width="10%">
                            <f:facet name="header">
                                <t:outputText value="#{text['invoice.balance']}"/>
                            </f:facet>
                            <t:inputText id="balance" style="text-align: right" value="" disabled="true">
                                <f:convertNumber type="number" pattern="#,##0.00;(#,##0.00)"/>
                            </t:inputText>
                        </t:column>
                        <t:column width="10%">
                            <f:facet name="header">
                            </f:facet>
                            <h:commandLink actionListener="#{paymentForm.deleteInvoice}" value="Quitar" disabled="#{paymentForm.isView}">
                                <f:param id="invoiceId" name="invoiceId" value="#{indx}"/>
                            </h:commandLink>
                        </t:column>
                    </t:dataTable>
                </t:htmlTag>

                <t:saveState id="save1" value="#{paymentForm.payment}" />
                <t:saveState id="save2" value="#{paymentForm.invoices}" />
                <t:saveState id="save3" value="#{paymentForm.company}" />
                <t:saveState id="save4" value="#{paymentForm.companies}" />
                <t:saveState id="save5" value="#{paymentForm.pendingAmount}"/>
                <t:saveState id="save6" value="#{paymentForm.localPendingAmount}"/>

                <h:outputText/><h:outputText/>
                <h:panelGroup>
                    <t:htmlTag value="div" styleClass="group">
                        <t:htmlTag value="div" styleClass="left">
                            <h:inputText id="createdBy" disabled="true"
                                         value="#{paymentForm.payment.createdBy.fullName}"/>
                            <t:htmlTag value="p"><h:outputLabel for="createdBy" value="#{text['payment.createdBy']}"/></t:htmlTag>
                        </t:htmlTag>
                        <t:htmlTag value="div">
                            <h:inputText id="createdOn" disabled="true"
                                         value="#{paymentForm.payment.createdOn}"/>
                            <t:htmlTag value="p"><h:outputLabel for="createdOn" value="#{text['payment.createdOn']}"/></t:htmlTag>
                        </t:htmlTag>
                        <t:htmlTag value="div" styleClass="left">
                            <h:inputText id="modifiedBy" disabled="true"
                                         value="#{paymentForm.payment.modifiedBy.fullName}"/>
                            <t:htmlTag value="p"><h:outputLabel for="modifiedBy" value="#{text['payment.modifiedBy']}"/></t:htmlTag>
                        </t:htmlTag>
                        <t:htmlTag value="div">
                            <h:inputText id="modifiedOn" disabled="true"
                                         value="#{paymentForm.payment.modifiedOn}"/>
                            <t:htmlTag value="p"><h:outputLabel for="modifiedOn" value="#{text['payment.modifiedOn']}"/></t:htmlTag>
                        </t:htmlTag>
                    </t:htmlTag>
                </h:panelGroup>
            </h:panelGrid>
        </h:form>

        <script type="text/javascript">
                                                 Form.focusFirstElement($('paymentForm'));
                                                 highlightFormElements();
        </script>
        <script type="text/javascript">
            function printReceipt(id) {
                window.open('/suarte-web/documento.pdf?id=' + id + '&amp;type=receipt', 'Suarte', 'height=800,width=700,status=yes,toolbar=no,menubar=no,location=no,resizable=yes');
                return false;
            }
            function distribute() {
                var payment = $('paymentForm:amount').value;
                var moneda = $('paymentForm:currency').value;
                var invoices;
                if (moneda != "1"){
                    invoices = $('paymentForm:invoices:_ptotal').value;                       
                } else {
                    invoices = $('paymentForm:invoices:_plocaltotal').value;
                }
                payment = parseFloat(payment.replace(/\,/g, ''));
                invoices = parseFloat(invoices.replace(/\,/g, ''));
                                                
                if (payment > invoices) {
                    alert('El monto del pago excede el monto de las facturas');
                    $('paymentForm:amount').focus();
                    return false;
                }
                var total = payment;
                var tableRows = $('paymentForm:invoices').rows;
                var balance = 0;
                var payment = 0;
                var newBalance = 0;

                for (var i = 1; tableRows.length - 1 > i; i++) {
                    // Previous balance
                    balance = tableRows[i].cells[2].firstChild.value;
                    balance = parseFloat(balance.replace(/\,/g, ''));
                    if (total > balance) {
                        payment = balance;
                        total = total - balance;
                    } else {
                        payment = total;
                        total = 0;
                    }

                    newBalance = balance - payment;
                    tableRows[i].cells[4].firstChild.value = formatNumber(payment, 2);
                    tableRows[i].cells[5].firstChild.value = formatNumber(newBalance, 2);
                }
                return true;
            }
        </script>
    </f:view>
</html>